//
//  SwiftUIView.swift
//  STORYZJ_App
//
//  Created by zzzzzzzzzz on 2025/9/29.
//

import SwiftUI
import Translation

@available(iOS 18.0, *)
struct WEEKMO_TranslateAPISwiftUIView: View {
    @State private var configuration: TranslationSession.Configuration?
    @State var originalText:String
    var onTranslationComplete: ((String,Bool) -> Void)?

    init(configuration: TranslationSession.Configuration? = nil, originalText: String, onTranslationComplete: ((String,Bool) -> Void)? = nil) {
//        self.configuration = TranslationSession.Configuration(source: .init(identifier: "zh-Hans-CN"), target: .init(identifier: "en-US"))
//            self.configuration = TranslationSession.Configuration(source: .init(identifier: "en-US"), target: .init(identifier: "zh-Hans-CN"))

        self.configuration = TranslationSession.Configuration(source: nil, target: nil)
        self.originalText = originalText
        self.onTranslationComplete = onTranslationComplete


    }
    
    var body: some View {
        HStack{
            
        }.translationTask(configuration) { session in
            do {
                 let rep = try await session.translate(originalText)
                print(rep.sourceLanguage)
                print(rep.targetLanguage)
                onTranslationComplete?(rep.targetText,true)
                
            }catch{
                onTranslationComplete?("",false)

            }
        
        }
    }
}

//#Preview {
//    if #available(iOS 18.0, *) {
//        WEEKMO_TranslateAPISwiftUIView(originalText: "")
//    } else {
//        // Fallback on earlier versions
//    }
//}


@available(iOS 18.0, *)
@objc class WEEKMO_TranslateAPIFatherView:UIView{
    private var textToTranslate: String = ""
    private var hostingController: UIHostingController<WEEKMO_TranslateAPISwiftUIView>?
    typealias stringCallBackBool = (String,Bool) -> ()

    var transBlock:stringCallBackBool?
    
    @objc override init( frame: CGRect) {
        super.init(frame: frame)
//        self.isHidden = true
        updateSwiftUIView()
    }
    
    private func updateSwiftUIView() {
        // 移除旧的hosting controller
        hostingController?.view.removeFromSuperview()
        hostingController?.removeFromParent()
        
        // 创建新的SwiftUI视图，并设置翻译完成回调
        let swiftUIView = WEEKMO_TranslateAPISwiftUIView(
            originalText: textToTranslate,
            onTranslationComplete: { [weak self] (translatedText,isSuccess) in
                // 将翻译结果传递给transBlock
                self?.transBlock?(translatedText,isSuccess)
            }
        )
        
        hostingController = UIHostingController(rootView: swiftUIView)
        guard let hostingController = hostingController else { return }
        
//        hostingController.view.isHidden = true
        self.addSubview(hostingController.view)
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            hostingController.view.topAnchor.constraint(equalTo: self.topAnchor),
            hostingController.view.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            hostingController.view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            hostingController.view.trailingAnchor.constraint(equalTo: self.trailingAnchor)
        ])
    }
    
    @objc func uploadTranslateStr(str:String,callBack:@escaping stringCallBackBool){
        

        
        Task{
            await self.checkLanguageSupport(from: str, to: nil)
        }
        
        self.textToTranslate = str
        self.transBlock = callBack
        
        // 强制重新创建SwiftUI视图以更新文本
        updateSwiftUIView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func checkLanguageSupport(from source: String, to target: Locale.Language?) async {
        let availability = LanguageAvailability()
        do {
            let status = try await availability.status(for: source, to: target)
            switch status {
            case .installed:
                print("installed")
            case .supported:
                print("supported")
            case .unsupported:
                print("unsupported")
            @unknown default:
                print("Not supported")
            }
        }catch{
            print("none")
        }
        

    }
    
}
